import api from '@/api'
import store from '@/store'
// 素材库
const state = {
  materialList: [],
  categoryList: []
}

const Mutation = {
  GET_MATERIAL_LIST: 'GET_MATERIAL_LIST',
  GET_CATEGORY_LIST: 'GET_CATEGORY_LIST',
  SET_MATERIAL_NAME: 'SET_MATERIAL_NAME',
  SET_MATERIAL_RESET: 'SET_MATERIAL_RESET'
}

const mutations = {
  // 素材列表
  [Mutation.GET_MATERIAL_LIST](state, data) {
    state.materialList = data
  },
  // 分组列表
  [Mutation.GET_CATEGORY_LIST](state, data) {
    state.categoryList = data
  },
  // 修改素材的名字
  [Mutation.SET_MATERIAL_NAME](state, data) {
    let topicData = state.materialList.find(item => item.id === data.id)
    topicData.filename = data.title
  },
  // 重置数据
  [Mutation.SET_MATERIAL_RESET](state) {
    state.materialList = []
    state.categoryList = []
  }
}

const Action = {
  GET_MATERIAL_LIST: 'GET_MATERIAL_LIST',
  GET_CATEGORY_LIST: 'GET_CATEGORY_LIST'
}
const actions = {
  // 素材列表数据
  [Action.GET_MATERIAL_LIST]({ commit }, { params }) {
    return new Promise((resolve, reject) => {
      api.getUserTeacherMaterialList(
        params,
        res => {
          commit(Mutation.GET_MATERIAL_LIST, res.data.data)
          store.dispatch('paginate/setPaginate', {
            listRows: params.count,
            total: res.data.total
          })
          resolve(res)
        },
        error => {
          reject(error)
        }
      )
    })
  },
  // 分组列表数据
  [Action.GET_CATEGORY_LIST]({ commit }, { params }) {
    return new Promise((resolve, reject) => {
      api.getUserTeacherMaterialCategoryList(
        params,
        res => {
          resolve(res)
        },
        error => {
          reject(error)
        }
      )
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
